package com.xzcs.directive;

import com.xzcs.util.freemarker.DirectiveUtils;
import freemarker.core.Environment;
import freemarker.template.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

@Component("fl_select")
public class SelectDirective implements TemplateDirectiveModel {

	public Logger logger = LoggerFactory.getLogger(getClass());

	private String id;
	private String name;
	private String otherAttr;
	private String value;
	private String headLabel;
	private String headValue;

	public void execute(Environment env, Map params, TemplateModel[] loopVars,
                        TemplateDirectiveBody body) throws TemplateException, IOException {
		id = DirectiveUtils.getString("id", params);
		name = DirectiveUtils.getString("name", params);
		value = DirectiveUtils.getString("value", params);
		otherAttr = DirectiveUtils.getString("otherAttr", params);
		headLabel = DirectiveUtils.getString("headLabel", params);
		headValue = DirectiveUtils.getString("headValue", params);
		String optionLabel = DirectiveUtils.getString("optionLabel", params);
		String optionValue = DirectiveUtils.getString("optionValue", params);
		TemplateModel model = (TemplateModel) params.get("list");

		StringBuffer sb = new StringBuffer();
		if (model instanceof TemplateSequenceModel) {
			TemplateSequenceModel tsModel = (TemplateSequenceModel) model;
			sb.append(printSelectStart());
			for (int i = 0; i < tsModel.size(); i++) {
				TemplateHashModel model1 = (TemplateHashModel)tsModel.get(i);
				String label1 = optionLabel == null ? "" : DirectiveUtils.getString(model1.get(optionLabel));
				String value1 = optionValue == null ? "" : DirectiveUtils.getString(model1.get(optionValue));
				sb.append(printOption(label1, value1));
			}
			sb.append(printSelectEnd());
		}

		env.setVariable(DirectiveUtils.OUT_HTML, DirectiveUtils.getDefaultObjectWrapper().wrap(sb.toString()));
		body.render(env.getOut());
	}

	public String printSelectStart() {
		StringBuffer sb = new StringBuffer();
		sb.append("<select ");
		if (id != null)
			sb.append("id=\"" + id + "\" ");
		if (name != null)
			sb.append("name=\"" + name + "\" ");
		if (otherAttr != null)
			sb.append(otherAttr);

		sb.append(">");
		if (headLabel != null) {
			headValue = (headValue == null ? "" : headValue);
			sb.append("<option value='" + headValue + "'>");
			sb.append(headLabel + "</option>");
		}

		return sb.toString();
	}

	public String printSelectEnd() {
		StringBuffer sb = new StringBuffer();
		sb.append("</select>");
		return sb.toString();
	}

	public String printOption(String optionName, String optionValue) {
		StringBuffer sb = new StringBuffer();
		sb.append("<option value='" + optionValue + "' ");
		if (value != null && value.equals(optionValue)) {
			sb.append("selected=\"selected\"");
		}
		sb.append(">" + optionName + "</option>");
		return sb.toString();
	}
}
